package com.geezdata.cps.base.aop;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.exceptions.MyException;
import com.geezdata.cps.base.response.BaseResponse;


@ControllerAdvice
public class ApiControllerAdvice {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings("rawtypes")
	@ExceptionHandler(MyException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleBusinessException(MyException myException) {
        return BaseResponse.error(myException.getCode(), myException.getMessage());
    }

    @SuppressWarnings("rawtypes")
   	@ExceptionHandler(DataAccessException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleSqlException(DataAccessException dataAccessExcpetion) {
        logger.error(dataAccessExcpetion.getMessage(), dataAccessExcpetion);
        return BaseResponse.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), ErrorCode.INTERNAL_SERVER_ERROR.getDesc());
    }

    @SuppressWarnings("rawtypes")
	@ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleRuntimeException(RuntimeException runtimeException) {
        logger.error(runtimeException.getMessage(), runtimeException);
        return BaseResponse.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), runtimeException.getMessage());
    }
    
    @SuppressWarnings("rawtypes")
	@ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleBusinessException(MethodArgumentNotValidException validationException) {
        logger.error(validationException.getMessage(), validationException);
        return BaseResponse.error(ErrorCode.INVALID_PARAMS.getCode(), ErrorCode.INVALID_PARAMS.getDesc());
    }
}
